package com.njtcedu.microblog.common.util;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author neo
 */
public final class JSONBinder<T> {
    public static <T> JSONBinder<T> binder(Class<T> beanClass) {
        return new JSONBinder<T>(beanClass);
    }

    public static ObjectMapper createMapper() {
        ObjectMapper mapper = new ObjectMapper();
        SimpleDateFormat dateFormat = new SimpleDateFormat(Convert.DATE_FORMAT_DATETIME);
        mapper.setSerializationConfig(mapper.getSerializationConfig().withDateFormat(dateFormat));
        mapper.setDeserializationConfig(mapper.getDeserializationConfig().withDateFormat(dateFormat));
        mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector());
        return mapper;
    }

    private final Class<T> beanClass;

    private JSONBinder(Class<T> beanClass) {
        this.beanClass = beanClass;
    }

    public T fromJSON(String json) {
        ObjectMapper mapper = createMapper();
        try {
            return mapper.readValue(json, beanClass);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String toJSON(T object) {
        ObjectMapper mapper = createMapper();
        try {
            return mapper.writeValueAsString(object);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
